﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharedGenomics.Domain
{
    internal class DataTypeParser<T> : IDataTypeParser
    {
        protected delegate bool TryParse(string str, out T value);

        private TryParse _tryParseDelegate;

        protected DataTypeParser(TryParse tryParse)
        {
            this._tryParseDelegate = tryParse;
        }

        #region IDataTypeParser Members

        public bool CanParse(string s)
        {
            T value;
            return this._tryParseDelegate(s, out value);
        }

        public object Parse(string s)
        {
            T value;
            if (this._tryParseDelegate(s, out value))
                return value;
            else
                throw new ArgumentException(String.Format("Cannot parse '{0}' to type {1}", s, typeof(T).Name));
        }

        #endregion
    }

    internal class IntDataTypeParser : DataTypeParser<int>
    {
        internal IntDataTypeParser()
            : base(int.TryParse)
        {
        }
    }

    internal class DateTimeTypeParser : DataTypeParser<DateTime>
    {
        internal DateTimeTypeParser()
            : base(DateTime.TryParse)
        {
        }
    }

    internal class DoubleDataTypeParser : DataTypeParser<double>
    {
        internal DoubleDataTypeParser()
            : base(double.TryParse)
        {
        }
    }

    internal class StringDataTypeParser : DataTypeParser<string>
    {
        internal StringDataTypeParser()
            : base(StringDataTypeParser.TryParseImpl)
        {
        }

        internal static bool TryParseImpl(string s, out string value)
        {
            value = s;
            return true;
        }
    }
}
